<?php

class Wall_Api_Core extends Core_Api_Abstract
{

    protected $_pluginLoader;

    public function assemble($body, array$params = array())
    {
        $body = $this->getHelper('translate')->direct($body);

        preg_match_all('~\{([^{}]+)\}~', $body, $matches, PREG_SET_ORDER);
        foreach ($matches as $match)
        {
            $tag = $match[0];
            $args = explode(':', $match[1]);
            $helper = array_shift($args);

            $helperArgs = array();
            foreach ($args as $arg)
            {
                if (substr($arg, 0, 1) === '$')
                {
                    $arg = substr($arg, 1);
                    $helperArgs[] = (isset($params[$arg]) ? $params[$arg] : null);
                }
                else
                {
                    $helperArgs[] = $arg;
                }
            }

            $helper = $this->getHelper($helper);
            $r = new ReflectionMethod($helper, 'direct');
            $content = $r->invokeArgs($helper, $helperArgs);
            $content = preg_replace('/\$(\d)/', '\\\\$\1', $content);

            $body = preg_replace("/" . preg_quote($tag) . "/", $content, $body, 1);
        }

        return $body;
    }

    public function getPluginLoader()
    {
        if (null === $this->_pluginLoader)
        {
            $path = Engine_Api::_()->getModuleBootstrap('wall')->getModulePath();
            $this->_pluginLoader = new Zend_Loader_PluginLoader(array('Wall_Model_Helper_' => $path . '/Model/Helper/'));
        }

        return $this->_pluginLoader;
    }

    public function getHelper($name)
    {
        $name = $this->_normalizeHelperName($name);
        if (!isset($this->_helpers[$name]))
        {
            $helper = $this->getPluginLoader()->load($name);
            $this->_helpers[$name] = new $helper;
        }

        return $this->_helpers[$name];
    }

    protected function _normalizeHelperName($name)
    {
        $name = preg_replace('/[^A-Za-z0-9]/', '', $name);
        $name = ucfirst($name);
        return $name;
    }

    /**
     *  prevent too many connection from users request. hard code. 
     * 
     * @params $viewer
     */
    public function getViewerFriends($viewer)
    {
        $userid = $viewer->getIdentity();
        $prefix = Engine_Db_Table::getTablePrefix();
        $db = Engine_Db_Table::getDefaultAdapter();
        $result = array();

        $sql = "
				select u.user_id,u.username, u.displayname, f.service_id, f.storage_path from 
				{$prefix}users as u
				join {$prefix}user_membership as m on (u.user_id = m.user_id and m.resource_id={$userid} and m.active =1)
				left join {$prefix}storage_files as f on (f.parent_type = 'user' and f.type ='thumb.icon' and f.parent_file_id =  u.photo_id)
				limit 1000
				";

        foreach ($db->fetchAll($sql) as $user)
        {
            $user_id_or_username = $user['username'] == null ? $user['user_id'] : $user['username'];
            $result[] = array(
                'name' => str_replace('?', '', $user['displayname'] ? $user['displayname'] : $user['username']), // prepare for regular expression
                'l' => 'profile/' . $user_id_or_username,
                'st' => 'user',
                'id' => $user['user_id'],
                'photo' => $user['storage_path'] ? $user['storage_path'] : "application/modules/User/externals/images/nophoto_user_thumb_icon.png",
            );
        }
        return $result;
    }
    
    public function createList($viewer, $list_name, $uids)
    {
        $lists_table = Engine_Api::_()->getDbtable('lists', 'wall');
        $items_table = Engine_Api::_()->getDbtable('listItems', 'wall');

        $db = $lists_table->getAdapter();
        $db->beginTransaction();
        try
        {
            //Create list
            $last_insert_id = $lists_table->insert(array(
                'user_id' => $viewer->getIdentity(),
                'list_name' => $list_name));

            //Add items
            if (count($uids) > 0)
            {
                foreach ($uids as $friend_id)
                {
                    $items_table->insert(array(
                        'list_id' => $last_insert_id,
                        'object_type' => 'friend',
                        'object_id' => intval($friend_id)
                    ));
                }
            }

            $db->commit();
        }
        catch (Exception $e)
        {
            $db->rollBack();
            throw $e;
        }
    }

    public function updateList($viewer, $list_id, $list_name, $uids)
    {
        $lists_table = Engine_Api::_()->getDbtable('lists', 'wall');
        $items_table = Engine_Api::_()->getDbtable('listItems', 'wall');
        
        $db = $lists_table->getAdapter();
        $db->beginTransaction();
        try
        {
            //Update list
            $data = array(
                'list_name' => $list_name
            );

            $where = $lists_table->getAdapter()->quoteInto('list_id = ?', $list_id);
            $lists_table->update($data, $where);

            //Delete old list items
            $where = $items_table->getAdapter()->quoteInto('list_id = ?', $list_id);
            $items_table->delete($where);

            //Create new list items
            if (count($uids) > 0)
            {
                foreach ($uids as $uid)
                {
                    $items_table->insert(array(
                        'list_id' => $list_id,
                        'object_type' => 'friend',
                        'object_id' => intval($uid)
                    ));
                }
            }
            
            $db->commit();
        }
        catch (Exception $e)
        {
            $db->rollBack();
            throw $e;
        }
    }

    public function deleteList(){
        
    }
}
